use std::collections::HashMap;
use partymod::client::EntityClient;
use partymod::PartyModConfig;
use chrono::Utc;

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
    env_logger::init();
    
    let config = PartyModConfig {
        entsrv_host: "127.0.0.1".to_string(),
        entsrv_port: 50051,
        timeout_seconds: 30,
    };
    
    let mut client = EntityClient::new(config).await.map_err(|e| anyhow::anyhow!("连接失败: {}", e))?;
    
    println!("=== 检查ContactMech表现有数据 ===");
    
    match client.query_data("ContactMech", None, None, None, Some(10), Some(0)).await {
        Ok(rows) => {
            println!("ContactMech表中现有 {} 条记录:", rows.len());
            for (i, row) in rows.iter().enumerate() {
                println!("记录 {}: {:?}", i + 1, row.fields);
            }
        }
        Err(e) => {
            println!("查询ContactMech失败: {}", e);
        }
    }
    
    println!("\n=== 尝试创建ContactMech表 ===");
    match client.create_table("ContactMech", false).await {
        Ok(_) => {
            println!("✓ ContactMech表创建成功");
        }
        Err(e) => {
            println!("✗ 创建ContactMech表失败: {}", e);
        }
    }
    
    println!("\n=== 尝试插入新的ContactMech记录 ===");
    let mut data = HashMap::new();
    let unique_id = format!("DEBUG_CM_{}", chrono::Utc::now().timestamp_millis() % 100000);
    data.insert("contactMechId".to_string(), unique_id.clone());
    data.insert("contactMechTypeId".to_string(), "POSTAL_ADDRESS".to_string());
    data.insert("infoString".to_string(), "Debug Address New".to_string());
    println!("使用唯一ID: {}", unique_id);
    
    match client.insert_data("ContactMech", data).await {
        Ok(generated_id) => {
            println!("✓ ContactMech插入成功，生成ID: {}", generated_id);
        }
        Err(e) => {
            println!("✗ ContactMech插入失败: {}", e);
        }
    }
    
    println!("\n=== 再次检查ContactMech表数据 ===");
     
     match client.query_data("ContactMech", None, None, None, Some(10), Some(0)).await {
          Ok(rows) => {
              println!("ContactMech表中现有 {} 条记录:", rows.len());
              for (i, row) in rows.iter().enumerate() {
                  println!("记录 {}: {:?}", i + 1, row.fields);
              }
          }
          Err(e) => {
              println!("查询ContactMech失败: {}", e);
          }
      }
     
     println!("\n=== 检查ContactMechType表数据 ===");
     
     match client.query_data("ContactMechType", None, None, None, Some(10), Some(0)).await {
         Ok(rows) => {
             println!("ContactMechType表中现有 {} 条记录:", rows.len());
             for (i, row) in rows.iter().enumerate() {
                 println!("记录 {}: {:?}", i + 1, row.fields);
             }
         }
         Err(e) => {
             println!("查询ContactMechType失败: {}", e);
         }
     }
    
    Ok(())
}